/*
Copyright (c) 2008 SmashedApples 

Contributors.  See: http://smashedapples.googlecode.com/

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

package smashedapples.controls.form
{
	import mx.controls.TextInput;
	
	import smashedapples.events.FormControlEvent;
	import smashedapples.managers.EventManager;
	import smashedapples.validators.TextInputValidator;
	import mx.validators.NumberValidator;
	import mx.utils.ObjectProxy;
	import mx.utils.ObjectUtil;
	import mx.events.FlexEvent;
	
	
	import flash.events.Event;
	import flash.events.FocusEvent;
	import flash.text.TextField;
	import mx.controls.TextInput;


	public class TextInput extends mx.controls.TextInput implements IFormControl
	{
		
		
		
		private var _textInputValidator : TextInputValidator;
		
		
		[Bindable("TextInputValidatorChanged")]
	 	public function get textInputValidator():TextInputValidator
	 	{
	 		
	 		if (_textInputValidator == null)
	 		{
	 			_textInputValidator = new TextInputValidator()
	 			_textInputValidator.source = this;
	 			_textInputValidator.property = prop;
	 			 			
	 			//EventManager.dispatchEvent( new FormControlEvent( FormControlEvent.ValidatorCreated, this._textInputValidator) );
	 		}
	 		return _textInputValidator;
	 	}	 	
	 	
	 	public function set validateRequired(value:Boolean):void { this.textInputValidator.required = value; } 
		public function set validateRequiredErrorMsg(value:String):void { this.textInputValidator.requiredFieldError = value; } 
		public function set validateMaxLength(value:Number):void { this.textInputValidator.maxLength = value; } 
 		public function set validateMaxLengthErrorMsg(value:String):void { this.textInputValidator.tooLongError = value; } 
		public function set validateMinLengthErrorMsg(value:String):void { this.textInputValidator.tooShortError = value; } 
		public function set validateMinLength(value:Number):void { this.textInputValidator.minLength = value; } 


		public function TextInput():void
		{
			super();
			this.addEventListener(FlexEvent.CREATION_COMPLETE, CreationCompleteHandler );
			
			
			_textEmpty = true;
			addEventListener( Event.CHANGE, handleChange );
			addEventListener( FocusEvent.FOCUS_IN, handleFocusIn );
			addEventListener( FocusEvent.FOCUS_OUT, handleFocusOut );
			
			
		}
		
		

		private var _textEmpty:Boolean;
		private var _currentlyFocused:Boolean = false;
		
		private var _prompt:String = "";
		public function get prompt():String
		{
			return _prompt;
		}
	
		[Bindable]
		public function set prompt(value:String):void
		{
			_prompt = value;
			invalidateProperties();
		}
		private var _promptFormat:String = '<font color="#999999"><i>[prompt]</i></font>';
		public function get promptFormat():String
		{
			return _promptFormat;
		}
		public function set promptFormat( value:String ):void
		{
			_promptFormat = value;
			if ( _promptFormat.indexOf( "[prompt]" ) < 0 )
			{
				// TODO: Log error with the logging framework, or just use trace?
				//trace( "PromptingTextInput warning: prompt format does not contain [prompt] replacement code." );	
			}
			invalidateDisplayList();
		}
		
		[Bindable("textChanged")]
	    [CollapseWhiteSpace]
	    [NonCommittingChangeEvent("change")]
		override public function set text( value:String ):void
		{
			_textEmpty = (!value) || value.length == 0;
			super.text = value;
			invalidateDisplayList();
		}
	
		override public function get text():String
		{
			// If the text has changed
			if ( _textEmpty )
			{
				// Skip the prompt text value
				return "";
			}
			else
			{
				return super.text;
			}
		}
	
	
	
		private var _displayAsPassword:Boolean = false;
		
		override public function set displayAsPassword(value:Boolean):void {
			_displayAsPassword = value;
			super.displayAsPassword = value;
		}
		override public function get displayAsPassword():Boolean {
			return _displayAsPassword;
		}
	

		override protected function updateDisplayList( unscaledWidth:Number, unscaledHeight:Number ):void
		{
			// If the text is empty and a prompt value is set and the
			// component does not currently have focus, then the component
			// needs to display the prompt
			if ( _textEmpty && _prompt != "" && !_currentlyFocused )
			{
				if ( _promptFormat == "" )
				{
					super.text = _prompt;
				} 
				else
				{
					super.htmlText = _promptFormat.replace( /\[prompt\]/g, _prompt );
				}
				
				if(super.displayAsPassword) {
					//If we're showing the prompt and we have displayAsPassword set then
					//we need to set it to false while the prompt is showing.
					var oldVal:Boolean = _displayAsPassword;
					super.displayAsPassword = false;
					_displayAsPassword = oldVal;
				}
			}
			else {
				if(super.displayAsPassword != _displayAsPassword) {
					super.displayAsPassword = _displayAsPassword;
				}
			}
			
			super.updateDisplayList( unscaledWidth, unscaledHeight );
		}
	
	
		protected function handleChange( event:Event ):void
		{
			_textEmpty = super.text.length == 0;
		}

		protected function handleFocusIn( event:FocusEvent ):void
		{
			_currentlyFocused = true;
			
			// If the text is empty, clear the prompt
			if ( _textEmpty )
			{
				super.htmlText = "";
				// KLUDGE: Have to validate now to avoid a bug where the format 
				// gets "stuck" even though the text gets cleared.
				validateNow();
			}
		}
	

		protected function handleFocusOut( event:FocusEvent ):void
		{
			_currentlyFocused = false;
			invalidateDisplayList();
		}
		
		
		
		
		
		
		
		
		public function CreateToolTip():void
		{
			trace("CreateToolTip");
		}
		
		private function CreationCompleteHandler(event:FlexEvent):void
		{	
			
			this.iResetValue = this[prop];
			
		}
		
		private var iResetValue:*;
		public function reset():void
		{
			this[prop] = iResetValue;
			this.errorString = "";
		}
		
		
		
		private var _prop : String = "text";
		public function get prop():String
		{
			return _prop;
		}
		public function set prop(property:String):void
		{
			_prop = property;
		}
		public function get key():String
		{
			return this.id as String;
		}
		public function get val():*
		{
			return this[prop];
		}
		public function set val(value:*):void
		{
			this[prop] = value;
		}
		
		public function hasChanged():Boolean
		{		
			if(val == iResetValue)
				return false;
			return true;
		}
		
	}
}